# config.py

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import os
from dotenv import load_dotenv
from logging.config import dictConfig

load_dotenv(r'../config.env')


class Config:
    # 使用随机生成的密钥 (实际项目从环境变量获取)
    # 代理地址
    SECRET_KEY = os.getenv('SECRET_KEY', '19960220Guo')

    # JWT配置
    JWT_ALGORITHM = 'HS256'
    JWT_EXPIRATION_HOURS = 24

    # 日志配置
    LOG_DIR = "logs"
    LOG_FILE = "app.log"

    @classmethod
    def init_logging(cls):
        """初始化日志配置"""
        log_path = os.path.join(cls.LOG_DIR, cls.LOG_FILE)
        os.makedirs(cls.LOG_DIR, exist_ok=True)

        dictConfig({
            'version': 1,
            'formatters': {
                'default': {
                    'format': '[%(asctime)s] %(levelname)s in %(filename)s:%(lineno)d - %(message)s',
                }
            },
            'handlers': {
                'file': {
                    'class': 'logging.handlers.RotatingFileHandler',
                    'filename': log_path,
                    'maxBytes': 1024 * 1024 * 50,  # 50 MB
                    'backupCount': 2,
                    'formatter': 'default'
                },
                'console': {
                    'class': 'logging.StreamHandler',
                    'formatter': 'default'
                }
            },
            'root': {
                'level': 'INFO',
                'handlers': ['file', 'console']
            }
        })



class DevelopmentConfig(Config):
    DEBUG = True
    # 开发环境MQTT配置
    # MQTT_BROKER_URL = '47.104.12.218'
    # MQTT_BROKER_PORT = 1883
    # MQTT_USERNAME = 'admin'
    # MQTT_PASSWORD = 'public'
    MQTT_BROKER_URL = 'mq.lianyuniot.com'
    MQTT_BROKER_PORT = 1883
    MQTT_USERNAME = 'LY_FFJ'
    MQTT_PASSWORD = 'FFJ371522'
    MQTT_KEEPALIVE = 60
    MQTT_TLS_ENABLED = False
    MQTT_CLIENT_KWARGS = {
    "max_inflight_messages": 1000,  # 允许同时处理的消息数
    "max_queued_messages": 10000  # 队列最大容量
}

    # 创建数据库引擎（替换为你的数据库连接字符串）
    engine = create_engine('mysql+pymysql://mqtt_test:19960220Guo#@47.104.12.218/mqtt_test',
                           echo=False)  # echo=True 输出SQL日志

    # 创建会话工厂
    Session = sessionmaker(bind=engine)
    session = Session()  # 每次操作前创建新会话

    LOG_LEVEL = 'DEBUG'  # 开发环境输出更详细的日志


class ProductionConfig(Config):
    DEBUG = False
    # 生产环境MQTT配置
    MQTT_BROKER_PORT = 8883
    MQTT_USERNAME = os.getenv('MQTT_PROD_USER')
    MQTT_PASSWORD = os.getenv('MQTT_PROD_PASS')

    LOG_LEVEL = 'WARNING'  # 生产环境只记录警告及以上级别


# 环境映射关系
config = {
    'development': DevelopmentConfig,
    'production': ProductionConfig,
    'default': DevelopmentConfig  # 默认环境
}
